import { defineStore } from "pinia";

function loadModule(path: string) {
  const modules = import.meta.glob("../views/**/*.vue");
  let module;
  if (modules["../views/" + path]) {
    module = modules["../views/" + path];
  } else {
    module = modules["../views/error/404.vue"];
  }

  console.log("path", path);
  console.log("module", module);

  return module;
}

// 权限  permission
export const usePermission = defineStore("permission", {
  persist: true,
  //数据状态
  state: () => {
    return {
      // 菜单列表（根据用户权限）
      menuTreeList: [],
      //所有的常数项目
      constantsItems: [],
    };
  },

  //设置数据
  actions: {
    setMenuTreeList(menuTreeList: []) {
      this.menuTreeList = menuTreeList;
    },
    setConstantsItems(constantsItems: []) {
      this.constantsItems = constantsItems;
    },
  },

  //计算属性
  getters: {
    //获取用户菜单
    getMenus(): [] {
      // console.log("Store this.menuTreeList", this.menuTreeList);

      return this.menuTreeList as [];
    },

    //获取用户权限路由
    getRouter(): [] {
      const routerList = [];

      this.menuTreeList.forEach((firstLevelMenu) => {
        firstLevelMenu.children.forEach((secondLevelMenu) => {
          // alert("secondLevelMenu.menuName" + secondLevelMenu.menuName);
          routerList.push({
            meta: {
              title: secondLevelMenu.menuName,
            },
            path: secondLevelMenu.url,
            component: loadModule(secondLevelMenu.path),
          });
        });
      });

      return routerList;
    },

    //根据 类型 获取  常数项目
    getConstants(): ConstantsItem[] {
      return this.constantsItems;
    },
  },
});
